package com.addcn.android.design591.comm;

import android.content.Context;

import com.addcn.android.design591.utils.L;
import com.addcn.android.design591.utils.T;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by xuge on 2017/1/4.
 * 网络连接类
 */

public class OkHttpConn {

    /*
     * 回调接口
     */
    public interface OkHttpCallBack {

        public void success(Call call, Response response) throws IOException;

        public void fail(Call call, IOException e);

    }

    /**
     * 自己包装的get请求
     *
     * @param context
     * @param url
     * @param okHttpCallBack
     */
    public static void getOkhttp(final Context context, final String url, final OkHttpCallBack okHttpCallBack) {
        //先执行权限判断
        PermissionUtils.externalStorage(context, new PermissionUtils.PermissionCallBack() {
            @Override
            public void setOnPermissionListener(Boolean bo) {
                if (bo) {
                    OkHttpClient client = new OkHttpClient();
                    Request request = new Request.Builder()
                            .url(url)
                            .addHeader("user-agent", HttpUtils.getHttpHeader(context))
                            .build();

                    Call call = client.newCall(request);
                    call.enqueue(new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                            okHttpCallBack.fail(call, e);
                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            okHttpCallBack.success(call, response);
                        }
                    });
                }
            }
        });
    }
}
